const mongoose=require('mongoose');
const Cate=require('../models/cate.model');

exports.create=function(req, res, next) {
    const  cate =new Cate(req.body);
    cate.save().then((data)=>res.json(data));
  }

exports.update=function(req,res,next){
    const id=req.params.id;
    Cate.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
        res.json(data);
    })
}

function reverseTree(data,parentId){
    var result=[];
    var temp;
    var data =JSON.parse(JSON.stringify(data));

    for(var i in data){
        if(data[i].parentId ===parentId){
            result.push(data[i]);
            temp=reverseTree(data,data[i]._id);
            if(temp.length>0){
                data[i].children =temp;
            }
        }
    }
    return result;
}

exports.list=function(req,res,next){
    var type =req.params.type;
    Cate.find({type:type},function(err,data){
        if(data.length>0){
            res.json(reverseTree(data,null)[0].children);
        }

    })
}

exports.get=function(req,res,next){
    const id=req.params.id;
    Cate.findById(id).then(data=>{
        res.json(data);
    })
}

exports.removes=function(req,res,next){
    var ids=req.body.ids.split(',');
    if(ids.length>0){
       Cate.remove({_id:{$in:ids}}).then(data=>{
           res.json('数据删除');
        });
    }
}

